package com.liyunc.socket.keepalive.client;

import com.liyunc.socket.keepalive.entity.Packet;
import com.liyunc.socket.keepalive.entity.Type;
import com.liyunc.socket.webclient.logger.Logger;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class ClientSender {

    private final Socket sender;
    ObjectOutputStream sendMsg;
    private static ClientSender instance;

    public static ClientSender getInstance() throws Exception {
        if (instance == null) {
            synchronized (DstClient.class) {
                instance = new ClientSender();
            }
        }
        return instance;
    }

    private ClientSender() throws Exception {
        sender = new Socket(InetAddress.getLocalHost(), 8083);
        ObjectOutputStream sendMsg = new ObjectOutputStream(sender.getOutputStream());
    }

    public void sendHeart() {
        try {
            while (true) {
                //ObjectOutputStream sendMsg = new ObjectOutputStream(sender.getOutputStream());
                Packet packet = new Packet();
                Thread.sleep(5000);
                packet.setType(Type.HEART);
                packet.setData("HEART".getBytes(StandardCharsets.UTF_8));
                sendMsg.writeObject(packet);
                sendMsg.flush();
            }
        } catch (Exception e) {
            Logger.error(e.toString());
        }
    }

    public void send(byte[] data) {
        try {
            //ObjectOutputStream sendMsg = new ObjectOutputStream(sender.getOutputStream());
            Packet packet = new Packet();
            packet.setType(Type.OTHER);
            packet.setData(data);
            sendMsg.writeObject(packet);
            sendMsg.flush();
        } catch (IOException e) {
            Logger.error(e.toString());
        }
    }
}
